import * as assert from 'assert';
import { Sequelize } from 'sequelize';
import { Umzug, SequelizeStorage } from 'umzug';
import databaseConfig from './config';

assert(databaseConfig !== null);
const sequelize = new Sequelize(databaseConfig);

const logger = process.env.TEST_LOG === 'log' ? console : undefined;

const createUmzug = () => {
  const { NODE_ENV } = process.env;
  let seeder;
  if (NODE_ENV === 'test') {
    seeder = new Umzug({
      migrations: {
        glob: [
          '{seeders/default-seeders/*.ts,seeders/test-seeders/*.ts}',
          { cwd: __dirname },
        ],
      },
      context: sequelize,
      storage: new SequelizeStorage({
        sequelize,
        modelName: 'seeder_meta',
      }),
      logger,
    });
  }
  if (NODE_ENV === 'production') {
    seeder = new Umzug({
      migrations: {
        glob: [
          '{seeders/default-seeders/*.ts,seeders/production-seeders/*.ts}',
          { cwd: __dirname },
        ],
      },
      context: sequelize,
      storage: new SequelizeStorage({
        sequelize,
        modelName: 'seeder_meta',
      }),
      logger,
    });
  }
  if (NODE_ENV === 'development') {
    seeder = new Umzug({
      migrations: {
        glob: [
          '{seeders/default-seeders/*.ts,seeders/development-seeders/*.ts}',
          { cwd: __dirname },
        ],
      },
      context: sequelize,
      storage: new SequelizeStorage({
        sequelize,
        modelName: 'seeder_meta',
      }),
      logger,
    });
  }
  return seeder;
};

export const migrator = new Umzug({
  migrations: {
    glob: ['migrations/*.ts', { cwd: __dirname }],
  },
  context: sequelize,
  storage: new SequelizeStorage({
    sequelize,
    modelName: 'migration_meta',
  }),
  logger,
});

export type Migration = typeof migrator._types.migration;

export const seeder = createUmzug();

export type Seeder = typeof seeder._types.migration;
